//
//  OtherSale.m
//  cutter
//
//  Created by mac on 16/3/3.
//  Copyright © 2016年 e360. All rights reserved.
//
#import "OtherCenter.h"
#import "OtherOrder.h"
#import "OtherSale.h"
#import "OtherCart.h"


//
//
@implementation OtherSaleDetail
- (void)viewDidLoad {
    [super viewDidLoad];
    [self headerRefresh:nil];
}
-(void)headerRefresh:(TMRefresh*)sender{
    __weak OtherSaleDetail *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        id temp = [OtherCart convertData:[this.data objectForKey:@"products"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            UITreeNode *root = [this makeNodesWithData:[NSDictionary dictionaryWithObject:temp forKey:@"items"] level:-1];
            [this.tableView setRootNode:root];
            [this updata];
        });
    });
}
-(UITreeNode*)makeNodesWithData:(id)data level:(NSInteger)level{
    static NSInteger identify = 0;
    if ([data isKindOfClass:NSDictionary.class]) {
        UITreeNode *nodes=[[UITreeNode alloc] init];
        nodes.idetify = identify++;
        nodes.level = level;
        nodes.expand = YES;
        nodes.select = NO;
        nodes.value = data;
        //子级列出
        id child = [data objectForKey:@"items"];
        if (child) {
            for (id item in child) {
                [nodes addNode:[self makeNodesWithData:item level:level+1]];
            }
        }
        return nodes;
    }
    return nil;
}
-(void)treeView:(UITreeView *)treeView expandRowAtIndex:(NSInteger)index{
}
-(void)treeView:(UITreeView *)treeView collapseRowAtIndex:(NSInteger)index{
}
-(UITableViewCell *)treeView:(UITreeView *)treeView cellForRowAtIndex:(NSInteger)index{
    UITreeNode *node = [treeView nodeAtIndex:index];
    if (node.level == 0) {
        OtherOrderHead *cell = [treeView dequeueReusableCellWithIdentifier:@"headIdentifier"];
        [cell.nameView setText:[node.value objectForKey:@"name"]];
        return cell;
    }
    if (node.level == 1) {
        OtherOrderHead *cell = [treeView dequeueReusableCellWithIdentifier:@"nameIdentifier"];
        [cell.nameView setText:[node.value objectForKey:@"name"]];
        return cell;
    }
    //
    id detail = [node.value objectForKey:@"product_detail"];
    if ([[node.value objectForKey:@"productid"] intValue] > 0) {
        OtherOrderCellCell *cell = [treeView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
        [cell.countView setText:[AppData countToString:[node.value objectForKey:@"number"] lable:nil]];
        [cell.priceView setText:[AppData priceToString:[detail objectForKey:@"price"] lable:nil]];
        [cell.nameView setText:[AppData objToString:[detail objectForKey:@"productname"] lable:nil]];
        [cell.sizeView setText:[AppData objToString:[detail objectForKey:@"productsn"] lable:nil]];
        [cell.descTips setText:[AppData objToString:[detail objectForKey:@"remark"] lable:nil]];
        [AppData loadImage:[detail objectForKey:@"thumb400_jpg"] view:cell.iconView];
        return cell;
    }
    OtherOrderCellCell *cell = [treeView dequeueReusableCellWithIdentifier:@"otherIdentifier"];
    [cell.priceView setText:[AppData priceToString:[detail objectForKey:@"price"] lable:nil]];
    [cell.nameView setText:[AppData objToString:[detail objectForKey:@"remark"] lable:nil]];
    return cell;
}
-(CGFloat)treeView:(UITreeView *)treeView heightForRowAtIndex:(NSInteger)index{
    UITreeNode *node = [treeView nodeAtIndex:index];
    if (node.level < 2) {
        if ([[node.value objectForKey:@"name"] isEqualToString:@""]) {
            return 0;
        }
        return 40;
    }
    return 119;
}
-(void)updata{
    NSString *temp = @"<span style='font-family:Helvetica Neue;color:#4A4A4A;line-height:200%%'>"\
    "<span style='font-size:18px;font-weight:bold;'>订单装态：<span style='color:#4A4A4A'></span></span><br/>"\
    "<span style='font-size:14px;'>总价：%@<br/>首付：%@</span></span>";
    NSString *html = [NSString stringWithFormat:temp,
                      [AppData priceToString:[self.data objectForKey:@"saleprice"] lable:nil],
                      [AppData priceToString:[self.data objectForKey:@"money"] lable:nil]];
    [self.infoView setAttributedText:[self parseHtml:html]];
    //
    id addressjson = [TMJSON parse:[self.data objectForKey:@"addressjson"]];
    if (addressjson) {
        temp = @"<span style='font-family:Helvetica Neue;color:#4A4A4A;line-height:180%%'>"\
        "<span style='font-size:18px;font-weight:bold;'>收货人信息</span><br/>"\
        "<span style='font-size:14px;'>姓名：%@<br/>手机：%@<br/>地址：%@<br/>邮箱：%@</span></span>";
        html = [NSString stringWithFormat:temp,
                [addressjson objectForKey:@"truename"],
                [addressjson objectForKey:@"mobile"],
                [addressjson objectForKey:@"address"],
                [addressjson objectForKey:@"email"]];
        [self.receiverView setAttributedText:[self parseHtml:html]];
    }
}
- (NSAttributedString*)parseHtml:(NSString*)html{
    NSDictionary *options = [NSDictionary dictionaryWithObject:NSHTMLTextDocumentType forKey:NSDocumentTypeDocumentAttribute];
    return [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUnicodeStringEncoding] options:options documentAttributes:nil error:nil];
}
- (IBAction)exitTouch:(id)sender{
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
@end


//
@interface  OtherSaleCollection : UICollectionView
@end
@implementation OtherSaleCollection
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[self nextResponder] touchesBegan:touches withEvent:event];
    [super touchesBegan:touches withEvent:event];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    [[self nextResponder] touchesMoved:touches withEvent:event];
    [super touchesMoved:touches withEvent:event];
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[self nextResponder] touchesEnded:touches withEvent:event];
    [super touchesEnded:touches withEvent:event];
}
@end
//
@interface OtherSaleCellCell : UICollectionViewCell
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation OtherSaleCellCell
@end
//
//
@interface OtherSaleCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *dateView;
@property (weak, nonatomic) IBOutlet UILabel *identifierView;
@property (weak, nonatomic) IBOutlet UILabel *stateView;
@property (weak, nonatomic) IBOutlet UILabel *countView;
@property (weak, nonatomic) IBOutlet UILabel *priceView;
@property (weak, nonatomic) IBOutlet UIButton *deleteView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) NSMutableArray *image;
@property (strong, nonatomic) NSArray *data;
@end
@implementation OtherSaleCell
-(NSMutableArray *)image{
    if (_image == nil) {
        [self setImage:[NSMutableArray array]];
    }
    return _image;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    [self.image removeAllObjects];
    for (id item in self.data) {
        if ([[item objectForKey:@"productid"] intValue] > 0 && [[item objectForKey:@"hardpacked"] intValue] == 0) {
            [self.image addObject:item];
        }
    }
    return [self.image count];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    OtherSaleCellCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
    id item = [[self.image objectAtIndex:indexPath.item] objectForKey:@"product_detail"];
    [AppData loadImage:[item objectForKey:@"thumb400_jpg"] view:cell.imageView];
    return cell;
}
@end
//
//
@implementation OtherSale
- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self.tableView.headerView addTarget:self action:@selector(headerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.tableView.headerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.tableView.headerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.tableView.headerView setTitle:@"下拉刷新" forState:TMRefreshStateNormal];
    //
    [self.tableView.footerView addTarget:self action:@selector(footerRefresh:) forControlEvents:UIControlEventValueChanged];
    [self.tableView.footerView setTitle:@"正在刷新" forState:TMRefreshStateRefreshing];
    [self.tableView.footerView setTitle:@"释放更新" forState:TMRefreshStatePulling];
    [self.tableView.footerView setTitle:@"上拉翻页" forState:TMRefreshStateNormal];
    //
    [self.invoiceView addTarget:self action:@selector(typeTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.doneView addTarget:self action:@selector(typeTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.allView addTarget:self action:@selector(typeTouch:) forControlEvents:UIControlEventTouchUpInside];
    [self.payView addTarget:self action:@selector(typeTouch:) forControlEvents:UIControlEventTouchUpInside];
    //
    [self typeTouch:self.allView];
}
-(void)typeTouch:(UIButton*)sender{
    if (sender) {
        [self.invoiceView setSelected:NO];
        [self.doneView setSelected:NO];
        [self.allView setSelected:NO];
        [self.payView setSelected:NO];
        [sender setSelected:YES];
        //
        if (sender == self.allView) {
            [self.condition setValue:nil forKey:@"status"];
        }
        if (sender == self.payView) {
            [self.condition setValue:@(0) forKey:@"status"];
        }
        if (sender == self.invoiceView) {
            [self.condition setValue:@(1) forKey:@"status"];
        }
        if (sender == self.doneView) {
            [self.condition setValue:@(2) forKey:@"status"];
        }
    }
    //
    OtherCenter *center = (id)self.splitViewController;
    if ([center isKindOfClass:OtherCenter.class] && center.userCenterCtrl) {
        [self setClient:center.userCenterCtrl.client];
        [self headerRefresh:nil];
    }else{
        [self headerRefresh:nil];
    }
}
-(void)headerRefresh:(TMRefresh*)sender{
    if (sender == nil) {
        sender = self.tableView.headerView;
        [sender beginRefreshing];
    }
    //
    __weak OtherSale *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [this.condition setValue:@(1) forKey:@"page"];
        [this setData:[AppData userSale:this.condition]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender endRefreshing];
            [this.tableView.footerView setFinish:NO];
            //
            [this.tableView reloadData];
        });
    });
}
- (void)footerRefresh:(TMRefresh*)sender{
    __weak OtherSale *this = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSInteger p = [[self.condition objectForKey:@"page"] intValue] + 1;
        [this.condition setValue:@(p) forKey:@"page"];
        //
        NSArray *app = [AppData userSale:this.condition];
        [this.data addObjectsFromArray:app];
        dispatch_async(dispatch_get_main_queue(), ^{
            [sender setFinish:[app count]==0];
            [sender endRefreshing];
            //
            [this.tableView reloadData];
        });
    });
}
- (NSMutableDictionary *)condition{
    if (_condition == nil) {
        [self setCondition:[NSMutableDictionary dictionary]];
    }
    [_condition setValue:@(50) forKey:@"limit"];
    [_condition setValue:[self.client objectForKey:@"uuid"] forKey:@"clientuuid"];
    return _condition;
}
//
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.destinationViewController isKindOfClass:OtherSaleDetail.class]) {
        NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
        if (indexPath) {
            id item = [self.data objectAtIndex:indexPath.row];
            OtherSaleDetail *ctrl = segue.destinationViewController;
            [ctrl setData:item];
        }
    }
}
//
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    for (id item in self.data) {
        id product_arr = [item objectForKey:@"product_arr"];
        if (product_arr) {
            [item setValue:product_arr forKey:@"products"];
        }else{
            product_arr = [TMJSON parse:[item objectForKey:@"productjson"]];
            if (product_arr) {
                [item setValue:product_arr forKey:@"products"];
            }
        }
        for (id product in product_arr) {
            id raw = [product objectForKey:@"raw"];
            [product addEntriesFromDictionary:raw];
            //
            id detail = [product objectForKey:@"product_detail"];
            if (detail == nil) {
                [product setValue:raw forKey:@"product_detail"];
            }else{
                [detail addEntriesFromDictionary:raw];
            }
        }
        [item setValue:nil forKey:@"product_arr"];
        [item setValue:nil forKey:@"productjson"];
        [item setValue:nil forKey:@"raw"];
    }
    return [self.data count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *item = [self.data objectAtIndex:indexPath.item];
    OtherSaleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
    [cell.dateView setText:[AppData objToString:[item objectForKey:@"postdate"] lable:nil]];
    [cell.identifierView setText:[AppData objToString:[item objectForKey:@"salesn"] lable:nil]];
    [cell.deleteView addTarget:self action:@selector(deleteTouch:) forControlEvents:UIControlEventTouchUpInside];
    //
    [cell.countView setText:[AppData countToString:[item objectForKey:@"number"] lable:@"总数:"]];
    [cell.priceView setText:[AppData priceToString:[item objectForKey:@"saleprice"] lable:@"总价"]];
    [cell setData:[item objectForKey:@"products"]];
    [cell.collectionView reloadData];
    return cell;
}
- (void)deleteTouch:(UIButton*)sender{
    UIView *cell = sender;
    while (cell) {
        if ([cell isKindOfClass:UITableViewCell.class]) {
            break;
        }
        cell = [cell superview];
    }
    //
    if (cell) {
        NSIndexPath *indexPath = [self.tableView indexPathForCell:(id)cell];
        if (indexPath) {
            id item = [self.data objectAtIndex:indexPath.row];
            if (item) {
                NSString *msg = [NSString stringWithFormat:@"删除“%@”？", [item objectForKey:@"salesn"]];
                //
                __weak OtherSale *this = self;
                [UIAlertController show:nil message:msg buttons:@[@"删除",@"取消"] handler:^(UIAlertAction *action) {
                    if ([action.title isEqualToString:@"删除"]) {
                        [AppData userDeleteSale:item];
                        [this headerRefresh:nil];
                    }
                }];
            }
        }
    }
}
- (IBAction)exitTouch:(id)sender {
    IndexHomeCtrl *tabbar = (id)self.splitViewController;
    if ([tabbar isKindOfClass:IndexHomeCtrl.class]) {
        [tabbar showMenu];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}
@end
